package org.com.Config;

import Entity.Exceptionlistner;
import lombok.extern.slf4j.Slf4j;
import org.com.Service.IExceptionlistnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @Autowired
    private IExceptionlistnerService exceptionlistnerService;

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxUploadSizeExceeded(MaxUploadSizeExceededException e) {
        log.error("捕获到文件上传大小超限异常");
        WriteWithError(e);

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body("文件大小超过限制，请上传小于指定大小的文件");
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception e) {
        log.error("捕获到"+e.getClass().getName()+"异常");
        WriteWithError(e);

        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("服务器内部错误");
    }


    private void WriteWithError(Throwable e) {
        String directory = "error";
        String filename = directory + File.separator + "info.txt";

        // 确保目录存在
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdir();
            System.out.println("目录创建成功: " + directory);
        }

        String timestamp = java.time.LocalDateTime.now()
                .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        // 更详细的格式
        StringBuilder content = new StringBuilder();
        content.append("=== 异常报告 ===").append(System.lineSeparator());
        content.append("时间: ").append(timestamp).append(System.lineSeparator());
        content.append("异常类型: ").append(e.getClass().getName()).append(System.lineSeparator());
        content.append("异常信息: ").append(e.getMessage()).append(System.lineSeparator());
        content.append("----------------").append(System.lineSeparator());

        Exceptionlistner ex = new Exceptionlistner();
        ex.setErrorName(e.getClass().getName());
        ex.setErrorMessage(e.getMessage());
        ex.setErrorMethods(e.getStackTrace()[0].getMethodName());
        ex.setErrorType(e.getClass().getTypeName());

        exceptionlistnerService.save(ex);


        try (FileOutputStream fos = new FileOutputStream(filename, true)) {
            fos.write(content.toString().getBytes());
            System.out.println("文件写入成功: " + filename);
        } catch (IOException e1) {
            System.out.println("操作失败: " + e1.getMessage());
        }
    }
}
